<template>
  <!-- 商品详情 Good 组件 -->
  <div class="Good">
    <!-- 顶部栏 -->
    <van-nav-bar title="商品详情页" left-text="返回" left-arrow @click-left="onClickLeft" />

    <!-- good-content 部分 -->
    <div class="good-content">
      <!-- 商品图片 -->
      <div class="good-img">
        <img :src="productDetail.large_img" alt="">
      </div>

      <!-- 商品详情 -->
      <div class="good-info-box">
        <div class="good-info">
          <!-- 商品名称和价格 -->
          <div class="clearfix good-Tbox">
            <!-- 商品名称 -->
            <div class="good-name-box">
              <div id="good-name">{{productDetail.name}}</div>
              <div id="good-enname">{{productDetail.enname}}</div>
            </div>
            <!-- 商品价格 -->
            <div class="good-price-box">
              ￥{{productDetail.price}}
            </div>
          </div>
          <!-- 选择温度和糖 -->
          <div class="good-select-box clearfix" v-for="(item,index) in productDetail.rules" :key="index">

            <div class="select-type clearfix">
              <div class="type-title">{{item.title}}</div>
              <div class="type-btn" v-for="(v,i) in item.rule" :key="i" :class="{active1:item.ruleIndex==i}" @click="toRule(item,i)">
                {{v.title}}
              </div>
            </div>
          </div>
          <!-- 选择数量 -->
          <div class="good-select-count clearfix">
            <div class="count-text">
              选择数量
            </div>
            <!-- count++ count--要补上方法 -->
            <div class="count-number">
              <van-stepper theme="round" button-size="22" disable-input v-model="product.count" />

            </div>
          </div>
          <!-- 商品描述 -->
          <div class="good-detail">
            <div class="good-detail-head">商品描述</div>
            <div class="good-detail-content" v-for="(item,i) in productDetail.desc">{{(i+1)+'、'+item}}</div>
          </div>
        </div>
      </div>

    </div>

    <!-- 底部栏 -->
    <div class="good-btm-box">
      <van-goods-action>
        <van-goods-action-icon icon="bag" text="购物袋" :badge="shopbagCount" to="/main/shopbag" />
        <van-goods-action-icon :icon="isLike ? 'like' : 'like-o'" :text="isLike?'已收藏':'收藏'" :color="isLike?'#ED1C24':'#595C5A'" @click="toggleLike" />
        <van-goods-action-button type="warning" text="加入购物车" color="#85d5f4" @click="addShopcart" />
        <van-goods-action-button type="danger" text="立即购买" color="#1a73e8" @click=" buy(isBuy)" />
      </van-goods-action>
    </div>
  </div>
</template>

<script>
import '@/assets/less/goodinfo.less'
import request from '@/utils/reques'
import qs from 'qs'
export default {
  name: 'Good',
  created() {
    this.pid = this.$route.params.pid
    // console.log(this.pid)
    this.getGoodInfo()
    this.findLike()
    this.findShopBagCount()
  },
  data() {
    return {
      isBuy: false,
      // 购物袋数量
      shopbagCount: 0,
      shopbag_icon: {
        //购物袋
        title: '购物袋',
        name: 'shopbag',
        icon: 'shop',
        path: '/main/shopbag',
        inactiveImg: require('@/assets/images/shopbag.png'),
        activeImg: require('@/assets/images/shopbag_active.png')
      },
      // 定义商品的id
      pid: '',
      // 商品数量信息的存储
      product: {
        count: 1
      },

      // 商品详情的数据
      productDetail: {},
      // 是否收藏商品
      isLike: false
    }
  },
  methods: {
    toRule(item, i) {
      if (item.ruleIndex == i) {
        return
      }
      item.ruleIndex = i
    },
    async addShopcart() {
      let tokenString = localStorage.getItem('token')
      if (!tokenString) {
        this.$toast('请先登录')
        return this.$router.push({ name: 'Login' })
      }
      let data = {
        pid: this.pid,
        count: this.product.count,
        appkey: this.appkey,
        tokenString
      }
      let rs = []
      // 便利ProuctDetail.rules获取选择的商品规格
      this.productDetail.rules.map((v) => {
        rs.push(v.rule[v.ruleIndex].title)
      })
      data.rule = rs.join('/')

      const { data: res } = await request.post('/addShopcart', qs.stringify(data))
      // console.log(res)
      if (res.code == 3000) {
        if (!this.isBuy) {
          if (res.status == 1) {
            this.$toast('加入购物袋成功')
            this.findShopBagCount()
          }
        } else {
          this.$router.push({ name: 'Pay', query: { sids: res.sid } })
        }
      }

      this.$toast.clear()
    },
    // 结算页面
    buy(isBuy) {
      this.isBuy = !this.isBuy
      this.addShopcart()
    },
    async findShopBagCount() {
      let tokenString = localStorage.getItem('token')
      if (!tokenString) {
        this.$toast('请先登录')
        return this.$router.push({ name: 'Login' })
      }
      const { data: res } = await request.get('/shopcartCount', { params: { appkey: this.appkey, tokenString } })
      // console.log(res)
      if (res.code == 4000) {
        // 赋值给shopBag
        this.shopbagCount = res.result
      }
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    async getGoodInfo() {
      // 轻加载提示要在方法里面使用
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      try {
        const { data: res } = await request.get('/productDetail', { params: { appkey: this.appkey, pid: this.pid } })
        // 要判断一下是不是600
        if (res.code == 600) {
          let data = res.result[0]
          // console.log(data)
          data.desc = data.desc.split(/\n/)
          // console.log(data.desc)

          let rules = []
          let rulesData = ['tem', 'sugar', 'milk', 'cream']

          rulesData.map((v) => {
            let r = {}
            r.title = data[v + '_desc']

            // 下标
            r.ruleIndex = 0
            r.rule = []

            // 获取规格的字符串
            let ruleString = data[v].split('/')

            ruleString.map((value) => {
              if (value != '') {
                r.rule.push({ title: value })
              }
            })
            if (r.rule.length > 0) {
              rules.push(r)
            }
          })

          data.rules = rules
          this.productDetail = data
          // console.log(this.productDetail)
        }
      } catch (error) {
        this.$toast.clear()
      }
    },
    // 查询商品的收藏状态
    async findLike() {
      try {
        let tokenString = localStorage.getItem('token')
        if (!tokenString) {
          this.$toast('请先登录')
          return this.$router.push({ name: 'Login' })
        }
        this.$toast.loading({
          message: '获取信息中',
          forbidClick: true,
          duration: 0
        })
        const { data: res } = await request.get('/findlike', { params: { appkey: this.appkey, pid: this.pid, tokenString } })
        // console.log(res)
        this.$toast.clear()
        if (res.code == 1000 && res.result.length > 0) {
          this.isLike = true
        }
      } catch (error) {
        this.$toast.clear()
      }
    },
    // 收藏商品
    async toggleLike() {
      try {
        let tokenString = localStorage.getItem('token')
        if (!tokenString) {
          this.$toast('请先登录')
          return this.$router.push({ name: 'Login' })
        }
        this.$toast.loading({
          message: '获取信息中',
          forbidClick: true,
          duration: 0
        })

        let url = this.isLike ? '/notlike' : 'like'
        const { data: res } = await request.post(url, qs.stringify({ appkey: this.appkey, pid: this.pid, tokenString }))
        // console.log(res)
        this.$toast.clear()
        if (res.code == 700) {
          this.$router.push({ name: 'Login' })
        } else if (res.code == 800) {
          this.isLike = true
        } else if (res.code == 900) {
          this.isLike = false
        }
        this.$toast(res.msg)
      } catch (error) {
        this.$toast.clear()
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>